package addressBook;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

class AdressBookXMLParser extends DefaultHandler {
	 
	Entry en;
	boolean IsFillingEntry = false;

    public void startElement(String namespaceURI, String localName, 
    						 String qName, Attributes atts)
    {	        
        if (qName.equals("entry")) {
        	IsFillingEntry = true;
        	en = new Entry(atts.getValue("LastName"),atts.getValue("Name"),atts.getValue("PatrName"));
        }
        else if (qName.equals("field") && IsFillingEntry) 
        	en.addField(atts.getValue("name"), atts.getValue("val"));
    }

    public void endElement(String namespaceURI, String localName,
                         String qName) {
    	if(qName.equals("entry")) {
    		IsFillingEntry = false;
    		AdressBook.getEntries().add(en);
    	}
    		
    }                                           
 
    public void warning(SAXParseException ex) {
        System.err.println("Warning at "+
				ex.getLineNumber()+" . "+
				ex.getColumnNumber()+"  -  "+
				ex.getMessage());
    }

    public void error(SAXParseException ex) {
        System.err.println("Error at {"+
				ex.getLineNumber()+" . "+
				ex.getColumnNumber()+"  -  "+
				ex.getMessage());
    }
    
    public void fatalError(SAXParseException ex) throws SAXException {
        System.err.println("Fatal error at {"+
				ex.getLineNumber()+" . "+
				ex.getColumnNumber()+"  -  "+
				ex.getMessage());
        throw ex;
    }

    public void printInfo() {
        System.out.println();
        System.out.println("Adress Book was succesfully loaded");
    }

}
